// CherryMerry ( Mikhail Tomilenko ), Reverse Entertainment, 2021-2024


#include <NifestGame/Core/Public/NF_PlayerController.h>
#include <NifestGame/Core/Public/NF_GameInstance.h>
#include <NifestGame/Core/Public/NF_Character.h>
#include <NifestGame/ActorComponents/Public/PlayerHealthManager.h>
#include <NifestGame/ActorComponents/Public/PlayerLevelManager.h>

#include <Kismet/GameplayStatics.h>

void ANF_PlayerController::InitializeNewGame_Implementation()
{
	ACharacter* LocalCharacter = SpawnPlayer();

	if (IsValid(LocalCharacter))
	{
		UE_LOG(LogTemp, Warning, TEXT("Character is valid"))

		UPlayerHealthManager* HealthManager = LocalCharacter->FindComponentByClass<UPlayerHealthManager>();
		UPlayerLevelManager* LevelManager = LocalCharacter->FindComponentByClass<UPlayerLevelManager>();

		if (IsValid(HealthManager) && IsValid(LevelManager))
		{
			UE_LOG(LogTemp, Warning, TEXT("Components is valid"))
			LevelManager->CurrentEXP = 0;
			LevelManager->CurrentLVL = 1;
			GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Black, FString::Printf(TEXT("CurrentLVL: %f"), LevelManager->CurrentLVL));

			HealthManager->CurrentHealth = LevelManager->GetHealthFromLVL(LevelManager->CurrentLVL);
			HealthManager->CurrentShield = LevelManager->GetShieldFromLVL(LevelManager->CurrentLVL);
		}
		else
		{
			UE_LOG(LogTemp, Warning, TEXT("Components is not valid"))
		}
	}
	else
	{
		UE_LOG(LogTemp, Warning, TEXT("Character is not valid"))
	}
}

void ANF_PlayerController::BeginPlay()
{
	Super::BeginPlay();

	UE_LOG(LogTemp, Warning, TEXT("SGTE_NewGame"))
	UGameInstance* GameInstance = UGameplayStatics::GetGameInstance(GetWorld());
	II_Core* CoreInterface = Cast<II_Core>(GameInstance);

	if (CoreInterface)
	{
		UE_LOG(LogTemp, Warning, TEXT("Interface is valid, level opened"))
		CoreInterface->Execute_LevelOpened(GameInstance);
	}
}

void ANF_PlayerController::OnPossess(APawn* aPawn)
{
	Super::OnPossess(aPawn);

	II_Core* CoreInterface = Cast<II_Core>(aPawn);
	if (CoreInterface)
	{
		CoreInterface->Execute_Initialize(aPawn);
	}
}

ACharacter* ANF_PlayerController::SpawnPlayer()
{
	/* Spawn location and rotation */
	FVector Location(-90.0f, -60.0f, 142.0f);
	FRotator Rotation(0.0f, 0.0f, 0.0f);

	/* Spawn info */
	FActorSpawnParameters SpawnInfo;

	/* Spawn player */
	ANF_Character* SpawnedPlayer = GetWorld()->SpawnActor<ANF_Character>(CharacterClass, Location, Rotation, SpawnInfo);

	if (IsValid(SpawnedPlayer))
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("SpawnedPlayer is valid!"));
	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("SpawnedPlayer is not valid!"));
	}

	return SpawnedPlayer;
}
